package com.kantboot.business.ac.listener;

import com.kantboot.business.ac.service.IBusAcCommonService;
import com.kantboot.functional.pay.order.event.PayEmitEvent;
import com.kantboot.functional.pay.order.module.dto.FunctionPayOrderDTOOfOrderPaidAfter;
import com.kantboot.functional.pay.order.module.entity.FunctionalPayOrder;
import com.kantboot.functional.pay.order.service.IFunctionalPayOrderService;
import com.kantboot.system.user.service.ISysUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class PayEmitByProductCodeIsRechargeVipOfYear {

    @Resource
    private IBusAcCommonService acCommonService;

    @Resource
    private ISysUserService userService;

    @Resource
    private IFunctionalPayOrderService payOrderService;

    public final static String PRODUCT_CODE = "rechargeVipOfYear";


    @EventListener
    public void onPayEmitEvent(PayEmitEvent payEmitEvent) {
        FunctionalPayOrder payOrder = payEmitEvent.getPayOrder();
        // 判断是否是充值vip的订单
        if (!PRODUCT_CODE.equals(payOrder.getProductCode())) {
            // 不是充值vip的订单，直接结束
            return;
        }
        // 判断是否充值成功
        if (!FunctionalPayOrder.STATUS_CODE_PAID.equals(payOrder.getStatusCode())) {
            // 不是充值成功的订单，直接结束
            return;
        }

        Double amount = payOrder.getAmount();
        Double rechargeVipOfYearPrice = acCommonService.getRechargeVipOfYearPrice();
        if(amount<rechargeVipOfYearPrice){
            log.info("充值vip的订单，金额不够，直接结束");
            FunctionPayOrderDTOOfOrderPaidAfter dto = new FunctionPayOrderDTOOfOrderPaidAfter();
            dto.setId(payOrder.getId());
            dto.setIsPaidAfterCheckSuccess(false);
            dto.setPaidAfterCheckFailReasonCode("amountNotEnough");
            dto.setPaidAfterCheckFailReasonDescription("金额错误");
            payOrderService.handlePaidAfter(dto);
            return;
        }
        log.info("充值vip的订单，金额够，开始处理");
        // 金额够，则设计为vip
        userService.addRole(payOrder.getUserId(), List.of("vip"));
        FunctionPayOrderDTOOfOrderPaidAfter dto = new FunctionPayOrderDTOOfOrderPaidAfter();
        dto.setId(payOrder.getId());
        dto.setIsPaidAfterCheckSuccess(true);
        payOrderService.handlePaidAfter(dto);
    }

}
